<?php
/**
 * Author: jikeSen
 * Email: 569045356@qq.com
 * WeChat: coco44886660
 * Date: 2018/4/10
 * Time: 下午4:21
 */

namespace app\api\service;

use app\common\Service;
use app\common\Utils\AliPay;
use app\common\Utils\BalancePay;
use app\common\Utils\WxPay;
use think\Db;

/**
 * 退款
 * Class FoundService
 * @package app\api\service
 */
class FoundService extends  Service
{
    /**
     * 退款
     * @param $order_id
     */
    public function drawBack($order_id)
    {
        #获取订单的信息
        $order_info = Db::table('sh_order')->find($order_id);

        if(!empty($order_info) &&  !in_array($order_info['status'],[2,5])){
            return [
                'code' => 'fail',
                'msg' => '该订单状态不可退款或已退款',
            ];
        }

        $refound_order = [];

        #捎货订单
        if($order_info['type'] == 1){

            $_order_info = Db::table('sh_order_info_shaohuo')->where('order_id',$order_id)->field('order_num,shipping_fee')->find();

            if(empty($_order_info)){
                return [
                    'code' => 'fail',
                    'msg' => '订单查询错误',
                ];
            }
            $refound_order['out_trade_no'] = $_order_info['order_num'];
            $refound_order['total_amount'] = $_order_info['shipping_fee'];//单位为分
        }

        if($order_info['type'] == 4){

            $_order_info = Db::table('sh_order_info_pay')->where('order_id',$order_id)->field('order_num,amount')->find();

            if(empty($_order_info)){
                return [
                    'code' => 'fail',
                    'msg' => '订单查询错误',
                ];
            }
            $refound_order['out_trade_no'] = $_order_info['order_num'];
            $refound_order['total_amount'] = $_order_info['amount'];//单位为分
        }


        #判断支付方式 选择退款渠道
        switch ($order_info['pay_type']) {
            case '0': #余额退款
                return BalancePay::refound($order_info);
                break;
            case '1': #支付宝
                $alipay = new AliPay();
                return $alipay->refound($refound_order);
                break;
            case '2': #微信app
                $wxpay = new WxPay($order_info['pay_type']);
                return $wxpay->refound($refound_order);
                break;
            case '4': #小程序
                $wxpay = new WxPay($order_info['pay_type']);
                return $wxpay->refound($refound_order);
                break;
            default:
                return ['code'=>'fail','msg'=>'部分不支持退款'];
        }
    }
}